package com.sencorsta.ids.pos;

import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessage;
import com.sencorsta.ids.core.tcp.socket.protocol.Header;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.Arrays;
import java.util.List;

/**
 * 请求消息解码类
 * @author ICe
 */
public final class PosDecoder extends ByteToMessageDecoder {

	private static int __RESPONSE_MAX_LEN = Integer.MAX_VALUE;
	
	public PosDecoder() {
		
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> packets) {
		if(in.readableBytes() < Header.SIZE) {
			return;
		}
		in.markReaderIndex();

		byte[] temp=new byte[in.readableBytes()];
		in.readBytes(temp);
		Out.trace("收到数据:",Arrays.toString(temp),"总长度",temp.length);
		Out.trace("Hex:" + My8583Ans.bytesToHexString(temp));
		Out.trace("String:" + new String(temp));
		in.resetReaderIndex();


		short len= in.readShort();
		Out.trace("长度:",len);
		if (len > __RESPONSE_MAX_LEN || len < 0) {
			Channel session = ctx.channel();
			Out.warn("包体长度错误");
			session.close();
			return;
		}
		if (in.readableBytes() < len) {
			in.resetReaderIndex();
			return;
		}
		in.resetReaderIndex();
		PosMassage msg=new PosMassage();
		msg.arr=new byte[in.readableBytes()];
		in.readBytes(msg.arr);
		packets.add(msg);
	}

}
